package com.common.app.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.common.app.R
import com.common.base.utils.ViewUtils


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2023/2/18
 *
 * 描述：联系电话数据适配器
 *
 * 修订历史：
 *
 */
class CommonContactNumberAdapter(context: Context, list: MutableList<String>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder?>() {
    private var mList: MutableList<String>
    private val con: Context

    /**
     * 布局
     */
    private val mInflater: LayoutInflater
    private var listener: OnCommonContactNumberAdListener? = null

    init {
        con = context
        mList = list
        mInflater = LayoutInflater.from(con)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {


        // 创建布局
        val typeView: View = mInflater.inflate(R.layout.item_common_contacct_number, parent, false)

        // 创建ViewHolder
        return CuViewHolder(typeView)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        setCuViewItem(holder as CuViewHolder, position)
    }

    /**
     * 蓝底项构造参数
     *
     * @param holder   持有类
     * @param position 项位置
     */
    private fun setCuViewItem(holder: CuViewHolder, position: Int) {

        // 获取设置各控件参数
        val bean = mList[position]
        holder.convertView.text = bean
        holder.convertView.tag = bean
    }

    override fun getItemCount(): Int {
        return mList.size
    }

    /**
     * 列表数据更新
     *
     * @param list
     */
    fun setData(list: MutableList<String>?) {
        if (list != null) {
            mList = list
            notifyDataSetChanged()
        }
    }

    /**
     * @param listener
     */
    fun setOnItemClickListener(listener: OnCommonContactNumberAdListener?) {
        this.listener = listener
    }

    /**
     *
     */
    interface OnCommonContactNumberAdListener {
        fun onCommonContactNumberAdClick(value: String?)
    }

    /**
     * 自定义ViewHolder，持有每个Item的的所有界面元素
     */
    inner class CuViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
        /**
         * 号码
         */
        var convertView: TextView

        init {
            convertView = itemView.findViewById(R.id.item_common_contacct_number_tv)
            convertView.setOnClickListener(this)
        }

        override fun onClick(v: View) {

            // 防止多次点击
            if (ViewUtils.isFastClick()) return
            
            when (v.id) {
                R.id.item_common_contacct_number_tv -> if (listener != null) {
                    val position = v.tag as String
                    listener?.onCommonContactNumberAdClick(position)
                }
                else -> {}
            }
        }
    }
}